/******************************************************************************
 * Copyright (C) 2017 ShenZhen
 * All Rights Reserved.
 *
 *****************************************************************************/

package cc.ycws.core.util;


import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;

/**
 * @author TODO
 * @Title:
 * @history 2017年11月9日 TODO 新建
 * @since JDK1.6
 */
public class EncryptUtils {

    public static String encryptString(String str) {
        return encryptString(str, Encrypt.MD5);
    }

    public static String encryptString(String str, Encrypt method) {
        String result = null;
        if (Encrypt.MD5.equals(method)) {
            result = getMD5(str);
        } else if (Encrypt.HMAC_SHA265.equals(method)) {
            result = getHamcSha265(str);
        }
        return result.toUpperCase();
    }

    public enum Encrypt {
        MD5,
        HMAC_SHA265
    }

    //生成MD5
    public static String getMD5(String message) {
        String md5 = "";
        try {
            // 创建一个md5算法对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageByte = message.getBytes("UTF-8");
            // 获得MD5字节数组,16*8=128位
            byte[] md5Byte = md.digest(messageByte);
            // 转换为16进制字符串
            md5 = bytesToHex(md5Byte);
        } catch (Exception e) {
            throw new RuntimeException("进行MD5加密时异常", e);
        }
        return md5;
    }

    //HAMC-SHA265加密
    public static String getHamcSha265(String message) {
        String result = "";
        try {
            String secret = "secret";
            SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(signingKey);
            result = bytesToHex(mac.doFinal(message.getBytes("UTF-8")));
        } catch (Exception e) {
            throw new RuntimeException("进行HMAC-SHA265加密时异常", e);
        }
        return result;
    }

    // 二进制转十六进制
    public static String bytesToHex(byte[] bytes) {
        StringBuffer hexStr = new StringBuffer();
        int num;
        for (int i = 0; i < bytes.length; i++) {
            num = bytes[i];
            if (num < 0) {
                num += 256;
            }
            if (num < 16) {
                hexStr.append("0");
            }
            hexStr.append(Integer.toHexString(num));
        }
        return hexStr.toString().toUpperCase();
    }
}